<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'my_reservations':
                // 获取我的预约列表
                $user = $auth->getCurrentUser();
                if (!$user) {
                    Response::authError('请先登录');
                }
                
                $reservations = $db->fetchAll("
                    SELECT r.*, ts.slot_name, ts.start_time, ts.end_time,
                           (SELECT COUNT(*) FROM reservation_companions WHERE reservation_id = r.id) as companion_count
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    WHERE r.user_id = ?
                    ORDER BY r.visit_date DESC, r.created_at DESC
                ", [$user['id']]);
                
                Response::success($reservations, '获取成功');
                break;
                
            case 'reservation_detail':
                // 获取预约详情
                $reservationId = (int)($_GET['id'] ?? 0);
                if (!$reservationId) {
                    Response::error('缺少预约ID');
                }
                
                $user = $auth->getCurrentUser();
                if (!$user) {
                    Response::authError('请先登录');
                }
                
                $reservation = $db->fetchOne("
                    SELECT r.*, ts.slot_name, ts.start_time, ts.end_time, u.nickname
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    LEFT JOIN users u ON r.user_id = u.id
                    WHERE r.id = ? AND r.user_id = ?
                ", [$reservationId, $user['id']]);
                
                if (!$reservation) {
                    Response::error('预约不存在');
                }
                
                // 获取同伴信息
                $companions = $db->fetchAll("
                    SELECT * FROM reservation_companions WHERE reservation_id = ?
                ", [$reservationId]);
                
                $reservation['companions'] = $companions;
                
                Response::success($reservation, '获取成功');
                break;
                
            case 'available_dates':
                // 获取可预约日期
                $startDate = $_GET['start_date'] ?? date('Y-m-d');
                $endDate = $_GET['end_date'] ?? date('Y-m-d', strtotime('+7 days'));
                
                $availableDates = [];
                $current = strtotime($startDate);
                $end = strtotime($endDate);
                
                while ($current <= $end) {
                    $dateStr = date('Y-m-d', $current);
                    $availability = checkDateAvailability($dateStr);
                    
                    // 获取当日总剩余名额
                    $totalAvailable = 0;
                    if ($availability['available']) {
                        $slots = $db->fetchAll("SELECT * FROM museum_time_slots WHERE is_active = 1 ORDER BY sort_order");
                        foreach ($slots as $slot) {
                            $slotAvailability = checkDateAvailability($dateStr, $slot['id']);
                            if ($slotAvailability['available']) {
                                $totalAvailable += $slotAvailability['available_slots'];
                            }
                        }
                    }
                    
                    $availableDates[] = [
                        'date' => $dateStr,
                        'day_of_week' => date('N', $current),
                        'day_name' => date('l', $current),
                        'available' => $availability['available'],
                        'reason' => $availability['reason'] ?? null,
                        'total_available' => $totalAvailable,
                        'schedule' => $availability['schedule'] ?? null
                    ];
                    
                    $current = strtotime('+1 day', $current);
                }
                
                Response::success($availableDates, '获取成功');
                break;
                
            case 'available_slots':
                // 获取某日期可用时段
                $visitDate = $_GET['date'] ?? '';
                if (!$visitDate) {
                    Response::error('缺少日期参数');
                }
                
                $slots = $db->fetchAll("SELECT * FROM museum_time_slots WHERE is_active = 1 ORDER BY sort_order");
                $availableSlots = [];
                
                foreach ($slots as $slot) {
                    $availability = checkDateAvailability($visitDate, $slot['id']);
                    if ($availability['available']) {
                        $slot['available_count'] = $availability['available_slots'];
                        $availableSlots[] = $slot;
                    }
                }
                
                Response::success($availableSlots, '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        $user = $auth->getCurrentUser();
        if (!$user) {
            Response::authError('请先登录');
        }
        
        switch ($action) {
            case 'create':
                // 创建预约
                if (!isset($input['visit_date']) || !isset($input['time_slot_id']) || !isset($input['visitor_count'])) {
                    Response::error('缺少必要参数');
                }
                
                $visitDate = $input['visit_date'];
                $timeSlotId = (int)$input['time_slot_id'];
                $visitorCount = (int)$input['visitor_count'];
                $visitorName = $input['visitor_name'] ?? $user['nickname'] ?? '';
                $visitorPhone = $input['visitor_phone'] ?? $user['phone'] ?? '';
                $visitorIdCard = $input['visitor_id_card'] ?? '';
                $notes = $input['notes'] ?? '';
                $companions = $input['companions'] ?? [];
                
                // 验证输入
                if ($visitorCount < 1 || $visitorCount > 10) {
                    Response::error('参观人数必须在1-10之间');
                }
                
                if (empty($visitorName) || empty($visitorPhone)) {
                    Response::error('参观者姓名和电话不能为空');
                }
                
                // 检查日期和时段可用性
                $availability = checkDateAvailability($visitDate, $timeSlotId);
                if (!$availability['available']) {
                    Response::error($availability['reason']);
                }
                
                if ($availability['available_slots'] < $visitorCount) {
                    Response::error('剩余名额不足，当前可预约：' . $availability['available_slots'] . '人');
                }
                
                // 检查用户是否已有该日期的预约
                $existingReservation = $db->fetchOne("
                    SELECT id FROM reservations 
                    WHERE user_id = ? AND visit_date = ? AND status IN ('pending', 'confirmed')
                ", [$user['id'], $visitDate]);
                
                if ($existingReservation) {
                    Response::error('您已预约该日期，请勿重复预约');
                }
                
                // 生成预约码
                $reservationCode = generateReservationCode();
                
                try {
                    // 开始事务
                    $db->getConnection()->beginTransaction();
                    
                    // 创建预约
                    $reservationId = $db->insert('reservations', [
                        'user_id' => $user['id'],
                        'reservation_type' => 'personal',
                        'visit_date' => $visitDate,
                        'time_slot_id' => $timeSlotId,
                        'visitor_count' => $visitorCount,
                        'visitor_name' => $visitorName,
                        'visitor_phone' => $visitorPhone,
                        'visitor_id_card' => $visitorIdCard,
                        'reservation_code' => $reservationCode,
                        'status' => 'confirmed',
                        'notes' => $notes
                    ]);
                    
                    if (!$reservationId) {
                        throw new Exception('创建预约失败');
                    }
                    
                    // 添加同伴信息
                    foreach ($companions as $companion) {
                        if (empty($companion['name'])) continue;
                        
                        $db->insert('reservation_companions', [
                            'reservation_id' => $reservationId,
                            'name' => $companion['name'],
                            'id_card' => $companion['id_card'] ?? '',
                            'phone' => $companion['phone'] ?? '',
                            'relationship' => $companion['relationship'] ?? ''
                        ]);
                    }
                    
                    // 更新统计
                    updateReservationStatistics($visitDate, $timeSlotId);
                    
                    // 提交事务
                    $db->getConnection()->commit();
                    
                    Response::success([
                        'reservation_id' => $reservationId,
                        'reservation_code' => $reservationCode,
                        'visit_date' => $visitDate,
                        'visitor_count' => $visitorCount
                    ], '预约成功');
                    
                } catch (Exception $e) {
                    $db->getConnection()->rollBack();
                    Response::error('预约失败：' . $e->getMessage());
                }
                break;
                
            case 'cancel':
                // 取消预约
                if (!isset($input['reservation_id'])) {
                    Response::error('缺少预约ID');
                }
                
                $reservationId = (int)$input['reservation_id'];
                
                $reservation = $db->fetchOne("
                    SELECT * FROM reservations 
                    WHERE id = ? AND user_id = ? AND status IN ('pending', 'confirmed')
                ", [$reservationId, $user['id']]);
                
                if (!$reservation) {
                    Response::error('预约不存在或无法取消');
                }
                
                // 检查是否可以取消（例如：参观前2小时不能取消）
                $visitDateTime = $reservation['visit_date'] . ' ' . ($reservation['start_time'] ?? '09:00:00');
                $cancelDeadline = strtotime('-2 hours', strtotime($visitDateTime));
                
                if (time() > $cancelDeadline) {
                    Response::error('参观前2小时内无法取消预约');
                }
                
                $result = $db->update('reservations', [
                    'status' => 'cancelled',
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = :id', ['id' => $reservationId]);
                
                if ($result) {
                    // 更新统计
                    updateReservationStatistics($reservation['visit_date'], $reservation['time_slot_id']);
                    Response::success(['reservation_id' => $reservationId], '取消成功');
                } else {
                    Response::error('取消失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}

// 生成预约码
function generateReservationCode() {
    return strtoupper(substr(md5(uniqid() . time()), 0, 12));
}

// 更新预约统计
function updateReservationStatistics($visitDate, $timeSlotId) {
    global $db;
    
    $stats = $db->fetchOne("
        SELECT 
            COUNT(CASE WHEN status IN ('pending', 'confirmed') THEN 1 END) as reserved_count,
            COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count,
            COUNT(CASE WHEN check_in_time IS NOT NULL THEN 1 END) as checked_in_count
        FROM reservations 
        WHERE visit_date = ? AND time_slot_id = ?
    ", [$visitDate, $timeSlotId]);
    
    $db->query("
        INSERT INTO reservation_statistics (visit_date, time_slot_id, reserved_count, cancelled_count, checked_in_count)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
        reserved_count = VALUES(reserved_count),
        cancelled_count = VALUES(cancelled_count),
        checked_in_count = VALUES(checked_in_count),
        updated_at = CURRENT_TIMESTAMP
    ", [
        $visitDate, 
        $timeSlotId, 
        $stats['reserved_count'], 
        $stats['cancelled_count'], 
        $stats['checked_in_count']
    ]);
}

// 复用之前的检查日期可用性函数
function checkDateAvailability($visitDate, $timeSlotId = null) {
    global $db;
    
    // 检查日期格式
    $dateObj = DateTime::createFromFormat('Y-m-d', $visitDate);
    if (!$dateObj) {
        return ['available' => false, 'reason' => '日期格式无效'];
    }
    
    $today = date('Y-m-d');
    if ($visitDate < $today) {
        return ['available' => false, 'reason' => '不能预约过去的日期'];
    }
    
    // 检查预约提前天数限制
    $advanceConfig = $db->fetchOne("SELECT config_value FROM museum_config WHERE config_key = 'advance_booking_days'");
    $advanceDays = (int)($advanceConfig['config_value'] ?? 7);
    $maxDate = date('Y-m-d', strtotime("+{$advanceDays} days"));
    if ($visitDate > $maxDate) {
        return ['available' => false, 'reason' => "只能预约{$advanceDays}天内的日期"];
    }
    
    // 检查是否为休息日
    $dayOfWeek = date('N', strtotime($visitDate)); // 1=周一, 7=周日
    $schedule = $db->fetchOne("SELECT * FROM museum_schedule WHERE day_of_week = ?", [$dayOfWeek]);
    if (!$schedule || !$schedule['is_open']) {
        return ['available' => false, 'reason' => '该日期为休息日'];
    }
    
    // 检查特殊闭馆日期
    $closure = $db->fetchOne("
        SELECT * FROM museum_closure_dates 
        WHERE is_active = 1 
        AND (
            (closure_type = 'once' AND closure_date = ?) 
            OR (closure_type = 'yearly' AND DATE_FORMAT(?, '%m-%d') = DATE_FORMAT(closure_date, '%m-%d'))
        )
    ", [$visitDate, $visitDate]);
    
    if ($closure) {
        return ['available' => false, 'reason' => '该日期为闭馆日：' . $closure['reason']];
    }
    
    // 检查预约人数限制
    if ($timeSlotId) {
        $slot = $db->fetchOne("SELECT * FROM museum_time_slots WHERE id = ? AND is_active = 1", [$timeSlotId]);
        if (!$slot) {
            return ['available' => false, 'reason' => '时段不存在或未启用'];
        }
        
        $reserved = $db->fetchOne("
            SELECT COALESCE(SUM(visitor_count), 0) as total 
            FROM reservations 
            WHERE visit_date = ? AND time_slot_id = ? AND status IN ('pending', 'confirmed')
        ", [$visitDate, $timeSlotId]);
        
        $availableSlots = $slot['max_visitors'] - ($reserved['total'] ?? 0);
        
        return [
            'available' => $availableSlots > 0,
            'available_slots' => $availableSlots,
            'max_visitors' => $slot['max_visitors'],
            'slot_info' => $slot
        ];
    }
    
    return ['available' => true, 'schedule' => $schedule];
}
?>